/*
  Temperature sensing with thermocouple and linear temp sensor
  
  Assumes slightly noisy thermocouple so applies a moving average
    window of 8 samples
  
  Requires a 10mV/C linear temperature sensor for cold compensation
  
  Method:
      Use a ring buffer to hold 8 thermocouple amplifier values
      Take the average of the buffer (1000x gain)
      Subtract a 2V offset
 */

const int amplifierPin = A0;
const int temperaturePin = A2;

float cjtLookup[] = {0.70924509994283,
0.72930601281847,
0.74938736853291,
0.76948922473255,
0.78961163711416,
0.80975465945405,
0.82991834363699,
0.85010273968481,
0.87030789578473,
0.89053385831746,
0.91078067188497,
0.93104837933801,
0.95133702180337,
0.97164663871086,
0.99197726782001,
1.01232894524655,
1.03270170548856};

void setup() {

  Serial.begin(9600);
}

void loop() {
  int buffer[8];  //averaging window
  char bufferP;
  
  //fill our averaging window with initial values
  for (int i=0; i<8; i++)
    buffer[i] = analogRead(amplifierPin);
    
  while (1) {
    //increment position in buffer
    if (++bufferP > 7)
      bufferP = 0;
    buffer[bufferP] = analogRead(amplifierPin);
    
    //get cold junction temperature
    float t = cjtLookup[analogRead(temperaturePin) - 37];

    //subtract amplifier offset, and get raw thermocouple output
    t += (average(buffer, 8) - 410)*(5.0/1024.0);
    
    //sends a reading in 1000x mV
    Serial.println(t);
    delay(500);
    
  }
}

//averages an array of integers
int average(int *b, int size) {
  int sum;
  for (int i=0; i<size; i++)
    sum += b[i];
    
  return sum/size;
}
